package com.hhdys.interceptor;

import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hhdys.annotation.Access;

public class DefaultInterceptor implements HandlerInterceptor  {
	
	Logger log=LogManager.getLogger(DefaultInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod=(HandlerMethod)handler;
		Class<? extends Object> beanClass = handlerMethod.getBean().getClass();
		Method method = handlerMethod.getMethod();
		
		Access methodAnnotation = method.getAnnotation(Access.class);
		Access classAnnotation=beanClass.getAnnotation(Access.class);
		if(classAnnotation==null){//没有页面权限限制
			return true;
		}
		if(methodAnnotation==null){//没有功能权限限制
			return true;
		}
		String classVal=classAnnotation.value();
		String methodVal=methodAnnotation.value();
		if(StringUtils.isBlank(classVal)||StringUtils.isBlank(methodVal)){
			return true;
		}
		Subject currentUser=SecurityUtils.getSubject();
		if(!currentUser.isPermitted(classVal+":"+methodVal)){//无权限
			String requestType = request.getHeader("X-Requested-With");//判断是否是ajax
			if(StringUtils.equals("XMLHttpRequest",requestType)){//是ajax访问
				request.setCharacterEncoding("utf-8");
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html;charset=utf-8");
				PrintWriter writer = response.getWriter();
				writer.write("{\"result\":\"error\",\"msg\":\"错误，您无权访问！\"}");
				return false;
			}
			request.setAttribute("msg", "您无权访问！");
			String errorPage="/admin/error.jsp";
			request.getRequestDispatcher(errorPage).forward(request, response);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
